package com.lambkit.simple.demo.app;

import cn.hutool.json.JSONUtil;
import com.lambkit.core.*;
import com.lambkit.core.task.app.AppTask;
import com.lambkit.core.task.app.AppTaskContext;
import com.lambkit.core.task.app.AppTaskInstance;
import com.lambkit.core.task.app.AppWorkCenter;

/**
 * @author yangyong(孤竹行)
 */
public class AppDemo {
    public static void main(String[] args) throws LifecycleException, InterruptedException {
        LambkitApp app = Lambkit.start(DefaultLambkitApp.class, AppDemo.class, args);
        if(app == null) {
            throw new RuntimeException("app start error");
        }

        //初始化工作中心
        AppWorkCenter workCenter = new AppWorkCenter();
        app.context().addWorkCenter(workCenter);
        //初始化任务
        workCenter.runOn(app)
                .addTask("/", AppTask.by(app.context().getBean(AppTaskValve001.class))
                        .addValve(app.context().getBean(AppTaskValve002.class)))
                .start();

        /////////////////////////////////////////////////////////////////////
        //执行任务
        String taskId = actionTask(app, "/");

        while (true) {
            AppTaskContext context = workCenter.getContext(taskId);
            if(context!=null) {
                System.out.println("task instance state: " + context.getCurrentState().toString());
                System.out.println("task instance message: " + context.getResult().getMessage());
                System.out.println("task instance result: " + JSONUtil.toJsonStr(context.getResult()));
                if(context.getCurrentState().equals(LifecycleState.STOPPED)) {
                    break;
                }
            } else {
                System.out.println("task instance not found");
            }
            Thread.sleep(100);
        }
        ///////////////////////////////////////////////////////////////////
        Lambkit.stop();
    }

    private static String actionTask(LambkitApp app, String target) {
        AppWorkCenter workCenter = app.context().getWorkCenter(AppWorkCenter.class);
        AppTask task = workCenter.route(target);
        AppTaskContext context = new AppTaskContext();
        context.setUri(target);
        context.setTask(task);
        //新任务
        AppTaskInstance taskInstance = new AppTaskInstance(context);
        //执行任务
        workCenter.execute(taskInstance);
        System.out.println("task id: " + task.getId());
        System.out.println("task instance id: " + taskInstance.getId());
        return taskInstance.getId();
    }
}
